package com.baoleme.interceptors;

import com.baoleme.exceptions.BusinessException;
import com.baoleme.exceptions.enumeration.ResponseEnum;
import com.baoleme.utils.JwtUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
    @Resource
    private JwtUtils jwtUtils;

    /*@Resource
    private RedisTemplate  redisTemplate;*/

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasLength(token)) {
            throw new BusinessException(ResponseEnum.TOKEN_MISSING);
        }
        if (!jwtUtils.validateToken(token, JwtUtils.SECRET_KEY)) {
            throw new BusinessException(ResponseEnum.INVALID_TOKEN);
        }
        return true;
    }
}
